package gsc

import (
	"errors"
	"log"
	"os"
	"sync"

	"github.com/istower/ssl_cert_auto/dns"
	"github.com/istower/ssl_cert_auto/ssl"
	"github.com/istower/ssl_cert_auto/utils"
	"github.com/spf13/cobra"
)

var (
	file     string
	domain   string
	path     string
	akid     string
	aksecret string
	Cmd      = &cobra.Command{
		Use:     "create",
		Short:   "create new cert",
		Long:    "创建一个阿里云免费ssl证书",
		Example: "gsc create -f ssl.yaml -d domain_name -i akid -s aksecret -p save_path",
		PreRun: func(cmd *cobra.Command, args []string) {
			setup()
			info()

		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return run()
		},
	}
)

func init() {
	Cmd.PersistentFlags().StringVarP(&file, "file", "f", "", "create ssl cert with provided configuration file")
	Cmd.PersistentFlags().StringVarP(&domain, "domain", "d", "", "ssl证书对应的域名记录")
	Cmd.PersistentFlags().StringVarP(&path, "path", "p", "", "write content to /tmp")
	Cmd.PersistentFlags().StringVarP(&akid, "id", "i", "", "阿里云AccessKey ID")
	Cmd.PersistentFlags().StringVarP(&aksecret, "secret", "s", "", "阿里云AccessKey Secret")
}

func info() {
	utils.Log.Println("开始任务")
}

func setup() {
	utils.LogInit()
}
func run() error {
	ak := GetAK()
	ssl.Init(ak)
	dns.Init(ak)

	var wg sync.WaitGroup
	if file != "" {
		//提供了文件，则文件信息优先
		certInfoList := utils.PaserFile(file)
		wg.Add(len(certInfoList.CertsInfo))
		for _, ci := range certInfoList.CertsInfo {
			certificateInfo := ssl.NewCertificateInfo(ci.Domain, ssl.ProduceCode, ssl.ValidateType, ci.Path)
			go func() {
				ssl.Operator(certificateInfo)
				wg.Done()
			}()

		}
	} else {
		if domain != "" {
			if path != "" {
				wg.Add(1)
				certificateInfo := ssl.NewCertificateInfo(domain, ssl.ProduceCode, ssl.ValidateType, path)
				go func() {
					ssl.Operator(certificateInfo)
					wg.Done()
				}()

			} else {
				wg.Add(1)
				certificateInfo := ssl.NewCertificateInfo(domain, ssl.ProduceCode, ssl.ValidateType, "/tmp")
				go func() {
					ssl.Operator(certificateInfo)
					wg.Done()
				}()
			}
		} else {
			return errors.New("必须指定配置文件或者是domain")
		}
	}
	wg.Wait()
	return nil
}

func GetAK() *utils.AccessKey {
	var (
		aliyun_id, aliyun_secret string
	)
	if akid != "" {
		aliyun_id = akid
	} else {
		aliyun_id = os.Getenv("ACCESSKEYID")
	}

	if aliyun_id == "" {
		log.Fatalln("未找到变量 ACCESSKEYID")
	}

	if aksecret != "" {
		aliyun_secret = aksecret
	} else {
		aliyun_secret = os.Getenv("ACCESSKEYSECRET")
	}

	if aliyun_secret == "" {
		log.Fatalln("未找到变量 ACCESSKEYSECRET")
	}

	return utils.NewAccessKey(aliyun_id, aliyun_secret)
}
